package com.alibaba.citrus.ots.b2b.trade.order.repository.impl;

import com.alibaba.citrus.ots.b2b.trade.order.repository.OrderQueryRepository;
import com.alibaba.citrus.ots.b2b.trade.order.repository.OrderWriteRepository;
import com.alibaba.citrus.ots.common.annotation.EpochTransactional;
import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.common.exception.RepositoryException;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.lattice2.epoch.db.service.CustomSequenceAccessor;
import com.alibaba.lattice2.epoch.middleware.mq.runtime.EpochMessageService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.epoch.app.bcots.contants.BcOtsConstants;
import com.epoch.app.bcots.platform_enhance.SaleOrderTag;
import com.epoch.app.otsb2btradecenter.domain.order.dto.*;
import com.epoch.app.otsb2btradecenter.domain.order.model.Order;
import com.epoch.app.otsb2btradecenter.domain.order.service.OrderService;
import com.epoch.app.otsb2btradecenter.domain.orderline.dto.CreateOrderLineResponse;
import com.epoch.app.otsb2btradecenter.domain.orderline.dto.OrderLineLoadListRequest;
import com.epoch.app.otsb2btradecenter.domain.orderline.dto.UpdateOrderLineResponse;
import com.epoch.app.otsb2btradecenter.domain.orderline.model.OrderLine;
import com.epoch.app.otsb2btradecenter.domain.orderline.service.OrderLineService;
import com.epoch.app.otsb2btradecenter.dto.request.OrderQueryRequest;
import com.epoch.app.otsb2btradecenter.enums.OrderStatus;
import com.epoch.app.otsb2btradecenter.model.dto.RejectOrderRequest;
import com.epoch.app.otsb2btradecenter.model.dto.TradeMessageSDO;
import com.epoch.app.otsb2btradecenter.sdo.OrderLineSDO;
import com.epoch.app.otsb2btradecenter.sdo.OrderSDO;
import com.epoch.app.otsb2btradecenter.sdo.PaymentInformationSDO;
import com.epoch.app.otsb2btradecenter.sdo.ScItemSDO;
import com.epoch.app.otsforecastsales.api.forecastorderwrite.service.ForecastOrderWriteService;
import com.epoch.app.otsforecastsales.dto.request.RefuseForecastDetailRequest;
import com.epoch.app.otsforecastsales.dto.request.RefuseForecastRequest;
import com.epoch.app.otsplatformenhance.dictionaryquery.service.DictionaryQueryService;
import com.epoch.app.otsplatformenhance.model.dto.BaseEnumDTO;
import com.epoch.app.otsplatformenhance.model.dto.QueryDictionaryRequest;
import com.google.common.collect.Lists;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Component
public class OrderWriteRepositoryImpl implements OrderWriteRepository {

    private Log log = Log.getLogger(OrderWriteRepositoryImpl.class);

//    private static CustomSequenceAccessor customSequenceAccessor;

    @Autowired
    private OrderService orderService;

    @Resource
    private OrderLineService orderLineService;
    @Autowired
    private CustomSequenceAccessor customSequenceAccessor;
    @Resource
    ForecastOrderWriteService forecastOrderWriteService;
    @Resource
    private DictionaryQueryService dictionaryQueryService;
    @Autowired
    private OrderQueryRepository orderQueryRepository;
    @Autowired
    private EpochMessageService messageService;

//    static {
//        customSequenceAccessor = SpringContextUtil.getBean(CustomSequenceAccessor.class);
//    }


    @RepositoryInvoker(printLog = true)
    @Override
    public String saveOrder(OrderSDO orderSDO) {
        Order request = createOrderConverter(orderSDO);
        CreateOrderResponse order = orderService.createOrder(request);
        log.info("OrderWriteRepositoryImpl  saveOrder"+JSONObject.toJSONString(request));
        if (order.getLastInsertId() == null) {
            log.error("OrderWriteRepositoryImpl$saveOrder_fail");
        }

        return order.getLastInsertId();
    }

    /*@Override
    public Boolean updateOrder(OrderSDO orderSDO) {
        Order order = createOrderConverter(orderSDO);
        order.setId(Long.parseLong(orderSDO.getId()));
        orderService.updateOrder(order);
        return true;
    }*/

    @Override
    @RepositoryInvoker
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean updateOrder(OrderSDO orderSDO) {
        Order order = createOrderConverter(orderSDO);
        order.setId(Long.parseLong(orderSDO.getId()));

        //查一把为了拿到版本号
        LoadOrderRequest loadOrderRequest = new LoadOrderRequest();
        loadOrderRequest.setId(orderSDO.getId());
        Order order1 = orderService.loadOrder(loadOrderRequest);
        order.setSyncVersion(order1.getSyncVersion());
        Map<String,String> lastFeatures = new HashMap<>();
        if (StringUtils.isNotBlank(order1.getFeatures())){
            lastFeatures = JSONObject.parseObject(order1.getFeatures(),Map.class);
            lastFeatures.putAll(orderSDO.getFeatures());
        }
        order.setFeatures(JSON.toJSONString(lastFeatures));

        UpdateOrderResponse updateOrderResponse = orderService.updateOrder(order);
        if (updateOrderResponse.getCount() != 1) {
            log.error("OrderWriteRepositoryImpl$updateOrder_fail");
            throw new RepositoryException("OTS-05-001-10-16-029");
        }
        return true;
    }

    @Override
    public Boolean updateOrderStatus(OrderSDO orderSDO) {
        LoadOrderRequest loadOrderRequest = new LoadOrderRequest();
        loadOrderRequest.setId(orderSDO.getId());
        Order order = orderService.loadOrder(loadOrderRequest);
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotEmpty(order.getFeatures())) {
            map = JSONObject.parseObject(order.getFeatures(), new TypeReference<Map<String, String>>() {
            });
        }
        map.put("outMaterialCertificateId", orderSDO.getFeatures().get("outMaterialCertificateId"));
        order.setFeatures(JSONObject.toJSONString(map));
        order.setStatus(orderSDO.getStatus());
        UpdateOrderResponse updateOrderResponse = orderService.updateOrder(order);
        if (updateOrderResponse.getCount() != 1) {
            throw new RuntimeException("modify order effect rows not 1!");
        }
        return true;
    }

    @Override
    @RepositoryInvoker
    @EpochTransactional(appCode="ots_b2b_trade_center", dataSourceCode = "cr_ots", dataSourceType = "app")
    public Boolean rejectOrder(RejectOrderRequest request) {
        LoadOrderRequest loadOrderRequest = new LoadOrderRequest();
        if (StringUtils.isNotBlank(request.getId())) {
            loadOrderRequest.setId(request.getId());
        }
        Order order = orderService.loadOrder(loadOrderRequest);
        order.setStatus(OrderStatus.COMPLETED.getCode());
        try {
            UpdateOrderResponse updateOrderResponse = orderService.updateOrder(order);
            if (updateOrderResponse.getCount() != 1) {
                log.error("OrderWriteRepositoryImpl$rejectOrder_fail");
                throw new RepositoryException("modify order effect rows not 1!");
            }
            //用于记录拒绝的所有子单
            List<String> orderLineIds = new ArrayList<>();
            OrderLineLoadListRequest orderLineLoadListRequest = new OrderLineLoadListRequest();
            orderLineLoadListRequest.setMainOrderId(request.getId());
            orderLineLoadListRequest.setStart(0);
            orderLineLoadListRequest.setLimit(999);
            Result<List<OrderLine>> listResult = orderLineService.loadOrderLineList(orderLineLoadListRequest);
            if (!CollectionUtils.isEmpty(listResult.getResult())) {
                List<OrderLine> orderLines = listResult.getResult().stream().map(orderLine -> {
                    orderLine.setRefuseReasonCode(request.getRejectReasonCode());
                    orderLine.setStatus(OrderStatus.COMPLETED.getCode());
                    return orderLine;
                }).collect(Collectors.toList());


                for (OrderLine orderLine : orderLines) {
                    UpdateOrderLineResponse updateOrderLineResponse = orderLineService.updateOrderLine(orderLine);
                    if (updateOrderLineResponse.getCount() != 1) {
                        log.error("OrderWriteRepositoryImpl$rejectOrder_fail");
                    }
                    orderLineIds.add(orderLine.getId().toString());
                }
                // 批量拒绝预报单
//                batchRefuseForecastLine(request,orderLines);
            }

            OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
            orderQueryRequest.setId(order.getId().toString());
            OrderSDO orderSDO = orderQueryRepository.querySingle(orderQueryRequest);
            TradeMessageSDO tradeMessageSDO = new TradeMessageSDO();
            tradeMessageSDO.setOrderSDO(orderSDO);

            tradeMessageSDO.setAffectLineIds(orderLineIds);
            String message = JSON.toJSONString(tradeMessageSDO);
            Map<String, String> map = new HashMap<>();
            map.put("_CZ_KEY", BcOtsConstants.TENANT_ID());
            messageService.sendMessage("sale_order_message", "CR_SALEORDER", "SaleRefused", orderSDO.getOrderBizId(), message, map);
            return true;
        } catch (Exception e) {
//            if (e instanceof FunctionException) {
//                log.error("预报订单拒绝失败");
//                throw new RepositoryException("OTS-05-001-10-16-006");
//            }
            log.error("销售订单拒绝失败", e);
            throw new RepositoryException("OTS-05-001-10-16-005");
        }
    }

    @Override
    @EpochTransactional(appCode="ots_b2b_trade_center", dataSourceCode = "cr_ots", dataSourceType = "app")
    public String saveOrderAndOrderLine(OrderSDO orderSDO) {
        log.info("OrderWriteRepositoryImpl   saveOrderAndOrderLine:" + JSONObject.toJSONString(orderSDO));

        if (Objects.isNull(orderSDO)) {
            throw new RepositoryException("OTS-05-001-10-16-026");
        }
        Order order = createOrderConverter(orderSDO);
        CreateOrderResponse orderResponse = orderService.createOrder(order);
        if (orderResponse.getLastInsertId() == null) {
            throw new RepositoryException("OTS-05-001-10-16-040");
        }
        if (CollectionUtils.isEmpty(orderSDO.getOrderLineSDOS())) {
            throw new RepositoryException("OTS-05-001-10-16-041");
        }

        try {
            List<CreateOrderLineResponse> collect = orderSDO.getOrderLineSDOS().stream().map(orderLineSDO -> {
                OrderLine orderLine = createOrderLineConverter(orderLineSDO,orderResponse.getLastInsertId());
                CreateOrderLineResponse orderLine1 = orderLineService.createOrderLine(orderLine);
                if (orderLine1.getLastInsertId() == null) {
                    throw new RepositoryException("OTS-05-001-10-16-042");
                }
                return orderLine1;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            throw new RepositoryException("OTS-05-001-10-16-042");
        }
        return orderResponse.getLastInsertId();
    }

    @Override
    public Boolean deleteOrder(String id) {
        if (StringUtils.isBlank(id)) {
          return false;
        }
        DeleteOrderRequest deleteOrderRequest = new DeleteOrderRequest();
        deleteOrderRequest.setId(id);
        DeleteOrderResponse deleteOrderResponse = orderService.deleteOrder(deleteOrderRequest);
        if (deleteOrderResponse.getCount() != 1) {
            return false;
        }
        return true;
    }

    private Result<Boolean> batchRefuseForecastLine(RejectOrderRequest request, List<OrderLine> orderLines) {
        // 销售子单为空，返回
        if (CollectionUtils.isEmpty(orderLines)) {
            return Result.success(Boolean.TRUE);
        }
        // 自建的销售子单，返回
        List<OrderLine> orderLineList = orderLines.stream().filter(orderLine -> StringUtils.isNotEmpty(orderLine.getFrontOrderLineId())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(orderLineList)) {
            return Result.success(Boolean.TRUE);
        }
        // 查询所有拒绝原因
        QueryDictionaryRequest dictionaryRequest = new QueryDictionaryRequest();
        dictionaryRequest.setDictCode("refuseReason");
        Result<List<BaseEnumDTO>> result = dictionaryQueryService.queryValues(dictionaryRequest);
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            throw new RuntimeException("查询拒绝原因为空");
        }
        Map<String, String> map = result.getResult().stream().collect(Collectors.toMap(BaseEnumDTO::getValue, BaseEnumDTO::getLabel, (key1, key2) -> key2));

        // 构建批量拒绝预报单入参
        List<RefuseForecastDetailRequest> refuseForecastDetailRequests = Lists.newArrayList();
        orderLineList.forEach(orderLine -> {
            RefuseForecastDetailRequest forecastDetailRequest = new RefuseForecastDetailRequest();
            forecastDetailRequest.setId(orderLine.getFrontOrderLineId());
            forecastDetailRequest.setRefuseReasonCode(request.getRejectReasonCode());
            forecastDetailRequest.setRefuseReason(map.get(request.getRejectReasonCode()));
            refuseForecastDetailRequests.add(forecastDetailRequest);
        });

        log.info("批量拒绝预报单入参:" + JSONObject.toJSONString(refuseForecastDetailRequests));
        RefuseForecastRequest forecastRequest = new RefuseForecastRequest();
        forecastRequest.setRefuseForecastDetailRequests(refuseForecastDetailRequests);
        return forecastOrderWriteService.batchRefuseForecast(forecastRequest);
    }


    private  Order createOrderConverter(OrderSDO orderSDO) {
        Order createRequest = new Order();
        if (StringUtils.isNotBlank(orderSDO.getId())) {
            createRequest.setId(Long.parseLong(orderSDO.getId()));
        }
        createRequest.setFrontOrderId(orderSDO.getFrontOrderId());
        createRequest.setAreaCode(orderSDO.getAreaCode());
        createRequest.setBisUnitCode(orderSDO.getBisUnitCode());
        createRequest.setSalesmanId(orderSDO.getSalesmanId());
        createRequest.setSalesmanName(orderSDO.getSalesmanName());
        createRequest.setOrderBizId(orderSDO.getOrderBizId());
        //获取序列编码
        if (orderSDO.getOrderBizId() == null) {
            if (StringUtils.isNotBlank(orderSDO.getOrderType())){
                String nextStringSequence = null;
                if (orderSDO.getOrderType().equals(SaleOrderTag.EXCHANGE_ORDER.getCode())) {
                    nextStringSequence = customSequenceAccessor.getNextStringSequence("ots_b2b_trade_center", "exchangeOrderSequence");
                } else if (orderSDO.getOrderType().equals(SaleOrderTag.LOGISTIC_RETURN_ORDER.getCode())
                        || orderSDO.getOrderType().equals(SaleOrderTag.STD_RETURN_ORDER.getCode())
                        || orderSDO.getOrderType().equals(SaleOrderTag.DS_STD_RETURN_ORDER.getCode())
                        || orderSDO.getOrderType().equals(SaleOrderTag.FREE_RETURN_ORDER.getCode())) {
                    nextStringSequence = customSequenceAccessor.getNextStringSequence("ots_b2b_trade_center", "returnOrderSequence");
                }else {
                    nextStringSequence = customSequenceAccessor.getNextStringSequence("ots_b2b_trade_center", "saleOrderSequence");
                }
                createRequest.setOrderBizId(nextStringSequence);
            }else {
                createRequest.setOrderBizId(orderSDO.getOrderBizId());
            }
        }
        createRequest.setOuterOrderId(orderSDO.getOuterOrderId());
        createRequest.setBizCode(orderSDO.getBizCode());
        createRequest.setBusinessCode(orderSDO.getBusinessCode());
        createRequest.setOrderType(orderSDO.getOrderType());
        //TODO 销售订单名称
        createRequest.setOrderTag(orderSDO.getOrderTag());
        createRequest.setCustomerCode(orderSDO.getCustomerCode());
        createRequest.setCustomerName(orderSDO.getCustomerName());
        createRequest.setOrganizationCode(orderSDO.getOrganizationCode());
        createRequest.setOrganizationName(orderSDO.getOrganizationName());
        createRequest.setDepartmentCode(orderSDO.getDepartmentCode());
        createRequest.setDepartmentName(orderSDO.getDepartmentName());
        createRequest.setProductGroupCode(orderSDO.getProductGroupCode());
        createRequest.setProductGroupName(orderSDO.getProductGroupName());
        createRequest.setSaleChannelCode(orderSDO.getSaleChannelCode());
        createRequest.setSaleChannelName(orderSDO.getSaleChannelName());
        createRequest.setChannelCode(orderSDO.getChannelCode());
        createRequest.setChannelName(orderSDO.getChannelName());
        createRequest.setReceiveAddressCode(orderSDO.getReceiveAddressCode());
        createRequest.setReceiveDetailAddress(orderSDO.getReceiveDetailAddress());
        createRequest.setStatus(orderSDO.getStatus());
        createRequest.setOrderTag(orderSDO.getOrderTag());
        createRequest.setCustomerAccounts(orderSDO.getCustomerAccounts());

        PaymentInformationSDO paymentInformationSDO = orderSDO.getPaymentInformationSDO();
        if (paymentInformationSDO != null) {
            createRequest.setOrderTotalFee(paymentInformationSDO.getOrderTotalFee());
            createRequest.setActualPaidFee(paymentInformationSDO.getActualPaidFee());
            createRequest.setShouldPayFee(paymentInformationSDO.getShouldPayFee());
            createRequest.setPostFee(paymentInformationSDO.getPostFee());
            createRequest.setPayStatus(paymentInformationSDO.getPayStatus());
            createRequest.setPayTime(paymentInformationSDO.getPayTime());
        }

        createRequest.setDeliveryStatus(OrderStatus.BEFORE_DELIVERY.getCode());
        createRequest.setEndTime(orderSDO.getEndTime());
        createRequest.setTransportModeCode(orderSDO.getTransportModeCode());
        createRequest.setTransportModeName(orderSDO.getTransportModeName());
        createRequest.setWareHouseCode(orderSDO.getWareHouseCode());
        createRequest.setWareHouseName(orderSDO.getWareHouseName());
        createRequest.setCustomerReferenceNo(orderSDO.getCustomerReferenceNumber());
        createRequest.setCustomerExpectDate(orderSDO.getCustomerExpectDate());
        createRequest.setCostCenter(orderSDO.getCostCenter());
        createRequest.setCashCustomerName(orderSDO.getCashCustomerName());
        createRequest.setSyncVersion(orderSDO.getSyncVersion());
        createRequest.setReverseReason(orderSDO.getReverseReason());
        createRequest.setCreateReason(orderSDO.getCreateReason());
        createRequest.setRemark(orderSDO.getRemark());
        createRequest.setGmtCreate(orderSDO.getGmtCreate());
        createRequest.setGmtModified(orderSDO.getGmtModified() == null ? new Date() : orderSDO.getGmtModified());
        createRequest.setCreatorName(orderSDO.getCreatorName());
        createRequest.setModifier(orderSDO.getModifierId());
        createRequest.setModifierName(orderSDO.getModifierName());
        createRequest.setContact(orderSDO.getContactor());
        createRequest.setContactPhone(orderSDO.getContactorPhone());
        createRequest.setSyncVersion(orderSDO.getSyncVersion());
//        if (orderSDO.getFeatures() != null) {
//            StringBuilder sb = new StringBuilder();
//            for (Map.Entry<String, String> entry : orderSDO.getFeatures().entrySet()) {
//                sb.append(entry.getKey());
//                sb.append(":");
//                sb.append(entry.getValue());
//                sb.append(";");
//            }
//            createRequest.setFeatures(sb.toString());
//        }
        String featuresStr = JSONObject.toJSONString(MapUtils.isEmpty(orderSDO.getFeatures()) ? new HashMap<>() : orderSDO.getFeatures());
        createRequest.setFeatures(featuresStr);

//        if (StringUtils.isNotBlank(orderSDO.getFeatureStr())) {
//            createRequest.setFeatures(orderSDO.getFeatureStr());
//        }
        return createRequest;
    }


    @RepositoryInvoker
    private  OrderLine createOrderLineConverter(OrderLineSDO orderLineSDO,String orderId) {
        OrderLine orderLine = new OrderLine();
        if (Objects.nonNull(orderLineSDO.getScItemSDO())) {
            orderLine.setScItemOutCode(orderLineSDO.getScItemSDO().getScItemOutCode());
        }

        orderLine.setMainOrderBizId(orderLineSDO.getMainOrderBizId());
        orderLine.setSerialNumber(orderLineSDO.getSerialNumber());
        orderLine.setMainOrderId(orderId);
        orderLine.setOrderLineTag(orderLineSDO.getOrderLineTag());
        orderLine.setBizCode(orderLineSDO.getBizCode());
        orderLine.setOuterOrderLineId(orderLineSDO.getOuterOrderLineId());
        orderLine.setCustomerCode(orderLineSDO.getCustomerCode());
        if (StringUtils.isNotBlank(orderLineSDO.getRefuseReasonCode())) {
            orderLine.setStatus(OrderStatus.COMPLETED.getCode());
        }else{
            orderLine.setStatus(orderLineSDO.getStatus());
        }
        orderLine.setPayStatus(orderLineSDO.getPayStatus());
        orderLine.setPayTime(orderLineSDO.getPayTime());

        ScItemSDO scItemSDO = orderLineSDO.getScItemSDO();

        if (scItemSDO != null) {
            orderLine.setCategoryCode(scItemSDO.getCategoryCode());
            orderLine.setCategoryDesc(scItemSDO.getCategoryDesc());
            orderLine.setCategoryChildCode(scItemSDO.getCategoryChildCode());
            orderLine.setCategoryChildDesc(scItemSDO.getCategoryChildDesc());

            orderLine.setFirstCategoryCode(scItemSDO.getFirstCategoryCode());
            orderLine.setFirstCategoryDesc(scItemSDO.getFirstCategoryDesc());
            orderLine.setSecondCategoryCode(scItemSDO.getSecondCategoryCode());
            orderLine.setSecondCategoryDesc(scItemSDO.getSecondCategoryDesc());
            orderLine.setSaleUnit(scItemSDO.getSaleUnit());
            orderLine.setSaleUnitName(scItemSDO.getSaleUnitName());
            orderLine.setInventoryUnitCode(scItemSDO.getInventoryUnitCode());
            orderLine.setInventoryUnit(scItemSDO.getInventoryUnitName());
            orderLine.setUnitConvert(scItemSDO.getUnitConvert());
            orderLine.setUnitPrice(scItemSDO.getUnitPrice() == null ? null :scItemSDO.getUnitPrice().toString());
            orderLine.setQuantity(scItemSDO.getQuantity());
            orderLine.setActivityPrice(scItemSDO.getActivityPrice() == null ? null :scItemSDO.getActivityPrice().toString());
            orderLine.setScItemId(scItemSDO.getScItemId());
            orderLine.setScItemTitle(scItemSDO.getScItemTitle());
            orderLine.setProductGroupCode(scItemSDO.getProductGroupCode());
            orderLine.setProductGroupName(scItemSDO.getProductGroupName());
            orderLine.setProductationTime(scItemSDO.getProductationTime());
        }
        orderLine.setShouldPayFee(null == orderLineSDO.getShouldPayFee() ? null : orderLineSDO.getShouldPayFee().toString());
        orderLine.setActualPaidFee(null == orderLineSDO.getActualPaidFee() ? null : orderLineSDO.getActualPaidFee().toString());
        orderLine.setDeliveryStatus(orderLineSDO.getDeliveryStatus());
        orderLine.setDeliveryTime(orderLineSDO.getDeliveryTime());
        orderLine.setEndTime(orderLineSDO.getEndTime());
        orderLine.setActivityCode(orderLineSDO.getActivityCode());
        orderLine.setActivityName(orderLineSDO.getActivityName());
        orderLine.setFrontOrderLineId(orderLineSDO.getFrontOrderLineId());
        orderLine.setRemark(orderLineSDO.getRemark());
        orderLine.setSyncVersion(orderLineSDO.getSyncVersion());

        orderLine.setRefuseReasonName(orderLineSDO.getRefuseReasonName());
        orderLine.setRefuseReasonCode(orderLineSDO.getRefuseReasonCode());
        orderLine.setDeliveryAmount(orderLineSDO.getDeliveryAmount());
        orderLine.setGmtCreate(orderLineSDO.getGmtCreate());
        orderLine.setGmtModified(orderLineSDO.getGmtModified() == null? new Date() : orderLineSDO.getGmtModified());
        orderLine.setCreatorId(orderLineSDO.getCreatorId());
        orderLine.setCreatorName(orderLineSDO.getCreatorName());
        orderLine.setModifierId(orderLineSDO.getModifierId());
        orderLine.setModifierName(orderLineSDO.getModifierName());
        orderLine.setReturnCharacter(orderLineSDO.getReturnCharacter());
        orderLine.setOrderLineTag(orderLineSDO.getOrderLineTag());
        orderLine.setCumulativeReceiptQuantity(orderLine.getCumulativeReceiptQuantity());
        orderLine.setCumulativeProcessingQuantity(orderLine.getCumulativeProcessingQuantity());

        if (MapUtils.isNotEmpty(orderLineSDO.getFeatures())) {
            String featureStr = JSONObject.toJSONString(orderLineSDO.getFeatures());
            orderLine.setFeatures(featureStr);
        }

        return orderLine;
    }
}
